#include "heard.h"


int main(){

    // read config
    char ip[MAXSIZE];
    if(getparameter("ip",ip) != 0){
        // error handling
        error(1,0,"config file");
    }
    char port[MAXSIZE];
    if(getparameter("port",port) !=0){
        error(1,0,"config file");
    }

    status_t pool;
    init_status(&pool, 4);
    
    //create socket
    int socket_fd;
    init_socket(&socket_fd,"192.168.85.129", "8080");

    //create epoll
    int ep_fd = epoll_create(1);
    add_epoll(ep_fd, socket_fd);

    while(1){
        // listening new client
        struct epoll_event events[2];
        memset(events, 0, sizeof(events));
        int num = epoll_wait(ep_fd, events, 2, -1);

        for(int i=0; i<num; i++){
            if(events[i].data.fd == socket_fd){
                // new client request connect
                int net_fd = accept(socket_fd, NULL, NULL);
                if(enqueue(&pool.b_queue, net_fd) != 0){
                    // queue full
                    char *err = "serve busy";
                    send(net_fd, err, sizeof(err), MSG_NOSIGNAL);
                    close(net_fd);
                    continue;
                }
                pthread_cond_broadcast(&pool.cond);
                continue;
            }
        }
    }


    return 0;
    
}
